<template>
  <div class="withdrawals_box body_sec">
    <div class="head">
      <nut-navbar class="navbar" z-index="5" :clickable="false" fixed safe-area-inset-top>
        <template #content>
          <span>{{ t('route_page_withdrawals') }}</span>
        </template>
        <template #left>
          <iconpark-icon style="rotate: 180deg;" @click="goToReplace" class="close" icon-id="you"
            size="1.2rem"></iconpark-icon>
        </template>
        <template #right>
          <!-- <div class="right_handler" style="display: none">
            <iconpark-icon name="refresh2" :class="refreshFlag && 'refresh'" size="1.5rem" @click="refresh" />
            <iconpark-icon v-if="eyeOpen" name="eye12" size="1.5rem" @click="changeEyeOpen(false)" />
            <iconpark-icon v-else name="hide" size="1.5rem" @click="changeEyeOpen(true)" />
          </div> -->
        </template>
      </nut-navbar>
    </div>

    <div class="content">
      <div class="withDraw_top bg_color">
        <div class="label_txt">
          <div>
            <p>{{ t('withdraw_page_withdrawMon') }}: </p>
            <p class="mon">
              &nbsp;{{ eyeOpen ? form.maxValue : hideText }}
            </p>
          </div>
          <div class="button_color to_page" @click="router.push(`/myWallet`)">{{ t('depositWithdraw') }}</div>
        </div>
        <div class="mon_sec">
          <div class="flex">
            <p> {{ `${t('withdraw_page_lockMon')}: ${verifyNumberComma(String(withdrawData.canot_withdraw))}` }}</p>
            <p @click="router.push(`/record?page=audit`)">
              {{ t('locked_info') }}
              <iconpark-icon icon-id="you" color="#C6C4F5" size=".875rem"></iconpark-icon>
            </p>
          </div>
          <p>{{ `${t('withdraw_page_turnover')}: ${verifyNumberComma(String(withdrawData.turnover))}` }}</p>
        </div>
        <div class="daiwancheng" v-if="showDaiWanCheng">{{ t('withdraw_page_fail_wait') }}...</div>
      </div>
      <nut-form label-position="top" ref="formRef" class="form_bg">
        <div class="bg_color form_center">
          <nut-form-item :label="withDrawType === 'usdt' ? t('pick_usdt') : t('walletInfo_page_selectBank')">
            <div class="change_bank">
              <div class="selectBank">
                <div class="bankName" v-show="backItemInfo.bank_name">
                  <div class="icon">
                    <ImgT :key="backItemInfo.bank_id" :src="`/imgs/bankIcon/bank_logo_${backItemInfo.bank_id}.webp`" />
                  </div>
                  <span>{{ backItemInfo.bank_name }}</span>
                </div>
                <div class="mantissa">
                  <span v-show="backItemInfo.account_number">
                    {{ withDrawType === 'usdt' ? backItemInfo.account_number :
                      maskTxtString(backItemInfo.account_number)
                    }}
                  </span>
                </div>
              </div>
              <nut-button :bordered="false" block class="change_btn button_color" @click="showChangeBank">
                {{ t('deposit_page_changeWay') }}
                <!--                <template #icon>
                  <iconpark-icon class="icon_jt" icon-id="you" size="1rem"></iconpark-icon>
                </template>-->
              </nut-button>
            </div>
          </nut-form-item>
        </div>
        <div class="bg_color form_third">
          <div class="flex justify-between label_top">
            <a>{{ t('withdraw_page_wit_mon') }}</a>
            <a class="flex" @click="router.push(`/record?page=withdraw`)">{{ t('mine_mywithdraw') }} <iconpark-icon
                icon-id="you" color="#5B6CFF" size=".875rem"></iconpark-icon></a>
          </div>
          <nut-form-item label="">
            <!-- <nut-input :disabled="true" @input="validateInput" v-model="form.amount" -->
            <nut-input v-if="loaded" :disabled="!loaded" @input="validateInput" v-model="form.amount"
              :placeholder="t('walletInfo_page_withdrawalMon') + '  ' + t('withdraw_atleast') + countMinMon()">
              <template #right>
                <span class="refresh_icon" @click="form.amount = ''">
                  <iconpark-icon icon-id="shuaxin" color="#504F6F" size="1.25rem"></iconpark-icon>
                </span>
              </template>
            </nut-input>
          </nut-form-item>
          <div v-show="removeComma(form.amount) > 0" class="projected flex ">
            <template v-if="withDrawType === 'usdt'">
              <p>{{ t('deposit_page_arrival') }}USDT: &nbsp;</p>
              <p>{{ verifyNumberComma(String(countUsdtMon(form.amount))) }}</p>
            </template>
            <template v-else>
              <p>{{ t('deposit_page_arrival') }}₫: &nbsp;</p>
              <p>{{ verifyNumberComma(String(form.amount)) }}</p>
            </template>
            <span v-if="withDrawType === 'usdt'">
              <nut-popover v-model:visible="showTips" location="top" bg-color="transparent" :show-arrow="false"
                :offset="[6, 3]">
                <template #reference>
                  <iconpark-icon name="Vector" color="#1DBA8B"></iconpark-icon>
                </template>
                <template #content>
                  <div class="pop_content"> {{ t('withdraw_page_usdt_tip') }}：{{ usdtObj.rate }}₫= 1USDT </div>
                </template>
              </nut-popover>

            </span>
          </div>
          <div class="flex kjje_div">
            <p class="kj_item" style="color: #fff;" v-for="(item, index) in chooseMoneyArr"
              @click="chooseFastMon(item.value)" :key="index">
              {{ item.label }}
            </p>
          </div>
          <nut-form-item>
            <template #label>
              <div class="label_capital">
                <p>{{ t('withdraw_page_payPwd') }}</p>
                <!-- 用于占位触发 -->
                <div class="zw_btn" @click="switchChange"></div>
                <nut-switch active-color="#0cc51e" inactive-color="#636a79" class="switch_password"
                  v-model="switchPassword" />
              </div>
            </template>
            <!-- 防止记住用户名和密码填充 -->
            <input v-if="loaded" :disabled="!loaded" type="password" class="hideInput" name="username-hide"
              autocomplete="off" />
            <!--            :type="!form.showConfirm ? 'password' : 'text'"-->
            <!-- <nut-input v-if="switchPassword" v-model="form.password" :placeholder="t('walletInfo_page_enterPayPwd')" -->
            <nut-input v-model="form.password" :placeholder="t('walletInfo_page_enterPayPwd')"
              type="number" :class="!form.showConfirm ? 'txt_password' : ''">
              <template #right>
                <div class="flex " @click="checkShowConfirm">
                  <iconpark-icon v-if="!form.showConfirm" name="hide" size="1.25rem"></iconpark-icon>
                  <iconpark-icon v-if="form.showConfirm" name="eye12" size="1.25rem"></iconpark-icon>
                </div>
              </template>
            </nut-input>
          </nut-form-item>
        </div>
      </nut-form>

      <div class="btn_zone flex ">
        <nut-button :bordered="false" class="submit_btn button_color pointer" block @click="onSubmit">{{
          t('walletInfo_page_immediately') }}
        </nut-button>
      </div>

      <div class="tips">
        <span class="icon" style="margin-right: 6px;">
          <iconpark-icon name="Vector" color="#D16262"></iconpark-icon>
        </span>
        <span> {{ t('walletInfo_page_tranferTips') }} </span>
      </div>
    </div>

    <nut-popup v-model:visible="addBankCardVisible" class="my_popup" position="bottom" :style="{ height: '78%' }">
      <AddBankCard @updateMyBankList="getMyBankList" :addBankCardVisible="addBankCardVisible"
        :bankListData="bankListData" @addBankCardVisible="addBankCardUse" :myBankData="myBankData"
        @openChooseBank="openChooseBank" />
    </nut-popup>
    <!-- 完善取款信息弹窗 -->
    <!--    <Teleport to="body">
      <nut-popup v-model:visible="calibrationVisible" class="bind_popup" position="bottom" :style="{ height: '90%' }">
        <CalibrationInfo :calibrationVisible="calibrationVisible" :bankListData="bankListData" :myBankData="myBankData"
          @openChooseBank="openChooseBank" @upDateAllList="upDateAllList" @closeCalibraWin="closeCalibraWin" />
      </nut-popup>
    </Teleport>-->

    <!-- 资金密码弹窗 -->
    <Modal v-model:visible="closeCapitalVisible" :title="t('home_page_fundPassword')">
      <div class="popup_body">
        <div class="form_card">
          <div class="form_container">
            <!-- :type="!capitalPassword.showConfirm ? 'password' : 'text'" -->
            <nut-input v-model="capitalPassword.value" :border="false" :placeholder="t('walletInfo_page_enterPayPwd')"
              type="number" :class="!capitalPassword.showConfirm ? 'txt_password' : ''">
              <template #right>
                <div class="flex " @click="() => { capitalPassword.showConfirm = !capitalPassword.showConfirm }">
                  <iconpark-icon v-if="!capitalPassword.showConfirm" name="hide" size="1.5rem"></iconpark-icon>
                  <iconpark-icon v-if="capitalPassword.showConfirm" name="eye12" size="1.5rem"></iconpark-icon>
                </div>
              </template>
            </nut-input>
          </div>
        </div>
        <div class="submit_btn">
          <div @click="capitalConfirm" class="button_color submit">{{ t('home_page_confirm') }}</div>
        </div>
      </div>
    </Modal>

    <!-- 选择银行弹窗 -->
    <chooseBankDialog ref="chooseBankModal" @selectBank="selectBank" />
    <!-- 保险箱弹框 -->
    <Modal v-model:visible="showSafeBox" :title="t('withdraw_alertTitle')" :zindex="1000">
      <view class="safe_box">
        <view class="content">
          <view class="safe_data">
            <view class="left">
              <view class="title">{{ t('wallet_type_map_1') }}</view>
              <view class="amount txt_ellipsis">{{ verifyNumberComma(String(roleInfo.money)) }}</view>
            </view>
            <view class="right">
              <view class="title">{{ t('walletInfo_page_central') }}</view>
              <view class="amount txt_ellipsis">{{ verifyNumberComma(String(roleInfo.bank_money)) }}</view>
            </view>
          </view>
          <view class="safe_money">
            <view class="title">{{ t('walletInfo_page_in') }}</view>
            <nut-input size="large" v-model="saveAmount" @input="validateSaveInput"
              :placeholder="t('bank_tip_empty_amount')">
              <template #right>
                <span class="refresh_icon" @click="saveAmount = ''">
                  <iconpark-icon icon-id="shuaxin" color="#504F6F" size="1.5rem"></iconpark-icon>
                </span>
              </template>
            </nut-input>
            <div class="flex kjje_div">
              <p class="kj_item" style="color: #fff;" v-for="(item, index) in choosePercent"
                @click="chooseSafeAmount(item.value)" :key="index">
                {{ item.label }}
              </p>
            </div>
            <div class="btn_zone flex ">
              <nut-button :bordered="false" class="submit_btn" block @click="handleTranMoney">{{
                t('walletInfo_page_in') }}
              </nut-button>
            </div>
            <div class="tips">
              <iconpark-icon name="Vector" color="#fff"></iconpark-icon>
              <span> {{ t('walletInfo_page_tranferTips') }} </span>
            </div>
          </view>
        </view>
      </view>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { showNotify } from "@nutui/nutui";
import { useI18n } from "vue-i18n";
import { onMounted, onUnmounted, ref, watch, defineAsyncComponent, computed } from "vue";
import AddBankCard from "@/views/withdrawals/component/addBankCard.vue";
// import CalibrationInfo from "./component/calibrationInfo.vue";
import PKwebsocket from "@/lolo/Ws";
import eventBus from "@/lolo/eventBus"
import { NetPacket } from "@/netBase/NetPacket";
import chooseBankDialog from '@/views/deposit/chooseBankDialog.vue';
import { removeComma, verifyNumberComma, maskTxtString } from "@/utils/publicMethods";
import { storeToRefs } from 'pinia';
import pinia from "@/store";
import { User } from '@/store/user';
import { showToast } from "@nutui/nutui";
import { useRouter, useRoute } from "vue-router";
import { Local } from "@/utils/storage.ts";

const Modal = defineAsyncComponent(() => import("@/components/Modal.vue"));

const router = useRouter();
const route = useRoute()
const { t } = useI18n();
const { bankCardInfoList } = storeToRefs(User(pinia));
const UserStore = User(pinia);
const { info: userInfo, roleInfo } = storeToRefs(UserStore);
const showTips = ref(false)
const closeCapitalVisible = ref(false)
const chooseBankModal = ref();
// 新增银行卡
const addBankCardVisible = ref(false)
// 校验弹窗
const calibrationVisible = ref(false)
const form = ref({
  maxValue: '0',
  amount: '',
  password: '',
  showConfirm: false
})
const withDrawType = ref(Local.get('curWithdrawWay')?.payname);
const usdtObj = ref({
  rate: 26540, // usdt 汇率,
});
const isCanWithdraw = ref(false)
const showDaiWanCheng = ref(false)
const withdrawData = ref({
  turnover: 0,
  canot_withdraw: 0, // 锁定金额
});

// 保险箱
const showSafeBox = ref(false)
const saveAmount = ref()
const choosePercent = [
  { label: '1/3', value: 3 },
  { label: '1/2', value: 2 },
  { label: t('promo_page_all'), value: 1 },
];
const bankListData = ref({ value: 0, label: '' });
const backItemInfo = ref({
  bank_id: 0,
  bank_name: '',
  account_number: ''
});
const myBankData: any = ref({
  list: [],
  cardholder_name: '',
  withdraw_pwd: '',
  phone: '',
  min_usdt: '',
  min_withdraw_money: '',
  max_withdraw_money: '',
  calibrationVisible: false,
})
const minNum = computed(() => {
  if (route.query.type == 'usdt') {
    return Number(myBankData.value.min_usdt || 0).toLocaleString()
  } else {
    return Number(myBankData.value.min_withdraw_money || 0).toLocaleString()
  }
  console.error(minNum)
})
const chooseMoneyArr = [
  { label: '100,000', value: 100000 },
  { label: '200,000', value: 200000 },
  { label: '500,000', value: 500000 },
  { label: '1,000,000', value: 1000000 },
  { label: '10,000,000', value: 10000000 },
  { label: '100,000,000', value: 100000000 },
];
const capitalPassword = ref({ value: '', showConfirm: false, });
const switchPassword = ref(false);

// 头部刷新
const refreshFlag = ref(false); //刷新标记
// 金额显示隐藏
const eyeOpen = ref(true); // 余额是否可见
const hideText = ref("*****")

// 限制只能输入输入数字
const validateInput = () => {
  form.value.amount = verifyNumberComma(String(form.value.amount.replace(/[^0-9]/g, "")));
};
// 保险柜金额
const validateSaveInput = () => {
  saveAmount.value = verifyNumberComma(String(saveAmount.value.replace(/[^0-9]/g, "")));
};
// 选择快捷金额
const chooseSafeAmount = (v: any) => {
  // 保险箱金额/v
  saveAmount.value = verifyNumberComma(String(parseInt(String(roleInfo.value.money / (+v)))))
}
// 存入保险柜
const handleTranMoney = () => {
  const numMon = removeComma(saveAmount.value);
  if (!numMon || numMon === 0) {
    return showNotify.danger(t('transfer_page_inputAmount'))
  }
  if (numMon > Number(roleInfo.value.money)) {
    return showNotify.danger(t('transfer_page_notEnough'))
  }
  const req: any = NetPacket.req_bank_save();
  req.money = removeComma(saveAmount.value);
  PKwebsocket.instance.send(req, true, {
    callbackName: 'msg_notify_bank_save_result',
    callback: handleGameToCenter
  })
};
const handleGameToCenter = (res: any) => {
  if (res.is_success === 1) {
    saveAmount.value = '' // 清空金额
    showNotify.success(t('proxy_page_caoZuo'))
  } else {
    showNotify.danger(t('proxy_page_caoZuoFail'))
  }
}

// 打开银行弹窗
const openChooseBank = () => {
  chooseBankModal.value.onCloseBank();
}

// 选择银行
const selectBank = (e: any) => {
  bankListData.value = e
  // chooseBank.value = e;
}
const showChangeBank = () => {
  if (withDrawType.value === 'usdt') {
    router.push(`/paymentManagement/usdt`)
  } else {
    // addBankCardVisible.value = !addBankCardVisible.value
    router.push(`/paymentManagement/bank`)
  }
}
// 选择银行信息
const addBankCardUse = (item: any, type: string,) => {
  let req: any;
  if (type === 'default') {//设为默认
    req = NetPacket.req_set_default_bankcard();
  } else if (type === 'del') {
    req = NetPacket.req_del_bank_card_info();
  }
  req.bankcard = `${item.bank_id}_${item.account_number}`;
  PKwebsocket.instance.send(req, true)
  addBankCardVisible.value = false
}

// 选择快捷金额
const chooseFastMon = (e: any) => {
  if (!form.value.amount) { form.value.amount = '0' }
  form.value.amount = removeComma(form.value.amount) + e;
  form.value.amount = verifyNumberComma(String(form.value.amount))
}

const checkShowConfirm = () => {
  form.value.showConfirm = !form.value.showConfirm
}
// 返回是否可以进行修改或绑定资金密码
const handleWithDrawClose = (res: any) => {
  const codeTxt: any = {
    1: t('开启资金密码成功'),
    2: t('withdraw_page_fail_tips2'),
    3: t('proxy_page_caoZuoFail'),
  }
  closeCapitalVisible.value = false
  // code 1 已关闭，2 已开启
  if (res.code == 1) {
    // showToast.success(codeTxt[res.code])
    switchPassword.value = false
  } else if (res.code == 2) {
    switchPassword.value = true
  } else if (res.message == "withdraw_password_operate_failed") {
    showToast.fail(codeTxt[res.code])
  }

}

const capitalConfirm = () => {
  if (!capitalPassword.value.value) return showToast.fail(t('walletInfo_page_enterPayPwd'))
  console.error(3)
  const req: any = NetPacket.req_open_or_close_withdraw_password()
  req.operate_type = switchPassword.value ? 2 : 1; // 1 开启，2 关闭, 3 查询是否开启资金密码
  req.role_id = roleInfo.value?.id
  req.withdraw_password = capitalPassword.value.value
  PKwebsocket.instance.send(req, true, {
    callbackName: 'msg_notify_open_or_close_withdraw_password',
    callback: handleWithDrawClose
  })
}

const switchChange = () => {
  if (switchPassword.value) { // 关闭
    closeCapitalVisible.value = true
  } else { // 开启
    const req: any = NetPacket.req_open_or_close_withdraw_password()
    req.operate_type = 1
    req.role_id = roleInfo.value?.id
    req.withdraw_password = capitalPassword.value.value
    PKwebsocket.instance.send(req, true, {
      callbackName: 'msg_notify_open_or_close_withdraw_password',
      callback: handleWithDrawClose
    })
  }
}

const onSubmit = () => {
  if (withDrawType.value !== 'usdt' && !backItemInfo.value.bank_id) {
    return showToast.fail(t('paymentManagement_page_chBank'))
  }
  if (withDrawType.value === 'usdt' && !backItemInfo.value.account_number) {
    return showToast.fail(t('paymentManagement_page_oneUsdt'))
  }
  const numMon = removeComma(form.value.amount);

  if (route.query.type == 'usdt') {
    if (numMon < Number(myBankData.value.min_usdt)) {
      return showToast.fail(t('withdraw_page_minAmount', { minAmount: verifyNumberComma(String(myBankData.value.min_usdt)) }))
    }
  } else {
    if (numMon < Number(myBankData.value.min_withdraw_money)) {
      return showToast.fail(t('withdraw_page_minAmount', { minAmount: verifyNumberComma(String(myBankData.value.min_withdraw_money)) }))
    }
  }


  if (numMon > Number(myBankData.value.max_withdraw_money)) {
    return showToast.fail(t('withdraw_page_maxAmount', { maxAmount: verifyNumberComma(String(myBankData.value.max_withdraw_money)) }))
  }
  console.log('------####', myBankData.value.calibrationVisible)
  if (myBankData.value.calibrationVisible) {
    // calibrationVisible.value = true
    goToWithdrawInfo();
  } else {
    handleSubmit()
  }
}

const handleSubmit = () => {
  const req: any = NetPacket.req_apply_withdraw();
  req.money = removeComma(form.value.amount);
  req.bank_card_id = backItemInfo.value.account_number || ''
  req.bank_id = backItemInfo.value.bank_id || 0;
  req.passwd = form.value.password || capitalPassword.value.value
  req.way = withDrawType.value === 'usdt' ? 2 : 1; // 1 银行卡，2 USTD
  PKwebsocket.instance.send(req, true, {
    callbackName: 'msg_notify_apply_withdraw',
    callback: handleWithDrawSubmit
  })
};

// 0=>申请成功, 1=>申请失败
const handleWithDrawSubmit = (res: any) => {
  const codeTxt: any = {
    0: t('withdraw_page_subSucces'),
    1: t('withdraw_page_fail_tips1'),
    2: t('withdraw_page_fail_tips2'),
    3: t('withdraw_page_fail_tips3'),
    4: t('withdraw_page_fail_tips4'),
    5: t('withdraw_page_fail_tips5'),
    6: t('withdraw_page_fail_tips6'),
  }
  if (res.result === 0) {
    showToast.success(codeTxt[res.result])
    router.push('/record?page=withdraw')
  } else {
    showToast.fail(codeTxt[res.result])
  }
}

const getMyBankList = () => {
  console.log('--获取最新银行------')
  const req = NetPacket.req_bank_card_info_list();
  PKwebsocket.instance.send(req, true)
}
const handleMyBankList = (res: any) => {
  console.log('==获取最新银行------', res)
  myBankData.value.calibrationVisible = !(res?.bank_card_info_list.length && userInfo.value.mobile && roleInfo.value.withdraw_pwd);
  // 银行卡提款
  if (withDrawType.value === 'bankcard_0') {
    if (!res?.bank_card_info_list.length) {
      goToWithdrawInfo();
      // calibrationVisible.value = true
      // myBankData.value.calibrationVisible = true
    } else {
      let list = res.bank_card_info_list.reverse();
      let data = list[0]
      backItemInfo.value.bank_id = data.bank_id
      backItemInfo.value.bank_name = data.bank_name
      backItemInfo.value.account_number = data.account_number
      myBankData.value.list = res?.bank_card_info_list || []
    }
    // myBankData.value.calibrationVisible = !(res?.bank_card_info_list.length && userInfo.value.mobile && roleInfo.value.withdraw_pwd);
  }

  if (!userInfo.value.mobile) {
    goToWithdrawInfo();
    // calibrationVisible.value = true
    // myBankData.value.calibrationVisible = true
  } else {
    console.log(1000001)
    myBankData.value.phone = userInfo.value.mobile
  }
  if (!roleInfo.value.withdraw_pwd) {
    console.log(1000002)
    goToWithdrawInfo();
    // calibrationVisible.value = true
    // myBankData.value.calibrationVisible = true
  } else {
    console.log(1000003)
    myBankData.value.withdraw_pwd = roleInfo.value.withdraw_pwd
  }
  myBankData.value.cardholder_name = res?.cardholder_name || ''
  myBankData.value.min_withdraw_money = res?.min_withdraw_money || 0
  myBankData.value.min_usdt = res?.min_usdt || 0
  myBankData.value.max_withdraw_money = res?.max_withdraw_money || 0
  myBankData.value.min_usdt = res?.min_usdt || 0
  Local.set("myBankData", myBankData.value)
}
// 获取已绑定的usdt地址
const getMyUsdtList = () => {
  const req = NetPacket.req_usdt_info_list();
  PKwebsocket.instance.send(req, true, {
    callbackName: 'msg_notify_usdt_info_list',
    callback: handleUsdtInfoRes
  })
}
const handleUsdtInfoRes = (res: any) => {
  console.log('usdt------', res)
  // 银行卡提款
  if (withDrawType.value === 'usdt') {
    let list = res.usdt_info_list.reverse();
    if (!list.length) {
      goToWithdrawInfo();
      // calibrationVisible.value = true
      // myBankData.value.calibrationVisible = true
    } else {
      let data = list[0]
      backItemInfo.value.account_number = data.usdt_addr
      myBankData.value.list = list
    }
    myBankData.value.calibrationVisible = !(list.length && userInfo.value.mobile && roleInfo.value.withdraw_pwd);
  }
  Local.set("myBankData", myBankData.value)
}

const handleCanWithdraw = (res: any) => {
  withdrawData.value.turnover = res?.turnover
  withdrawData.value.canot_withdraw = res?.canot_withdraw;
  const canMon = res.can_withdraw; // 可提现金额
  if (res.rlt == 2) {//有订单在处理中
    // 显示有待处理订单
    showDaiWanCheng.value = true
    isCanWithdraw.value = false
  } else {
    isCanWithdraw.value = true
    // 弹保险柜判断 保险柜<可提款金额时，弹   (还要满足不展示完善信息弹框)
    // if (roleInfo.value.bank_money < canMon && !calibrationVisible.value) {
    console.log('roleInfo.value.bank_money', roleInfo.value.bank_money)
    console.log('canMon', canMon)
    if (roleInfo.value.bank_money < canMon) {
      showSafeBox.value = true
    }
  }
  setCanWithDrawMon(canMon);
};
// 设置可提现金额
const setCanWithDrawMon = (val: any) => {
  if (isCanWithdraw.value) {
    form.value.maxValue = verifyNumberComma(String(val))
  } else { // 不可以提现，可提现金额置为 0
    form.value.maxValue = '0'
  }
}

const reqWithdrawPasswordStatus = () => {
  // 提现是否需要资金密码
  const req: any = NetPacket.req_open_or_close_withdraw_password()
  req.operate_type = 3
  req.role_id = roleInfo.value?.id
  req.withdraw_password = capitalPassword.value.value
  PKwebsocket.instance.send(req, true, {
    callbackName: 'msg_notify_open_or_close_withdraw_password',
    callback: handleWithDrawClose
  })
}
watch(roleInfo, (val: any) => {
  if (val && val.id) {
    reqWithdrawPasswordStatus()
  }
}, { immediate: true })
const initReq = () => {
  const req = NetPacket.req_can_withdraw()
  PKwebsocket.instance.send(req, true, {
    callbackName: 'msg_notify_can_withdraw',
    callback: handleCanWithdraw
  })
  refreshFlag.value = false
};



const handleDelBankList = (res: any) => {
  if (res.result === 0) {
    showToast.success(t('proxy_page_caoZuo'))
    getMyBankList();
  } else {
    showToast.fail(t('proxy_page_caoZuoFail'))
  }
}
// 设置默认银行
const handleDefaultBank = (res: any) => {
  if (res.rlt === 0) {
    showToast.success(t('proxy_page_caoZuo'))
    getMyBankList();
  } else {
    showToast.fail(t('proxy_page_caoZuoFail'))
  }
}

// const upDateAllList = () => {
//   getMyBankList()
//   getMyUsdtList()
// }
const getUsdtRate = () => {
  const req = NetPacket.req_usdt_and_revenue_ratio()
  PKwebsocket.instance.send(req, true, {
    callbackName: 'msg_notify_usdt_and_revenue_ratio',
    callback: handleUsdtRate
  })
}
const handleUsdtRate = (res: any) => {
  usdtObj.value.rate = res.u_ratio
}
// 计算usdt 金额
const countUsdtMon = (val: any) => {
  if (!usdtObj.value.rate) return
  const num = removeComma(String(val)) / usdtObj.value.rate;
  return num.toFixed(2)
}
// 计算越南盾 金额
const countVenMon = (val: any) => {
  if (!usdtObj.value.rate) return
  const num = removeComma(String(val)) * usdtObj.value.rate;
  return num.toFixed(2)
}
// 最低提款金额
const countMinMon = () => {
  if (withDrawType.value === 'usdt') {
    return verifyNumberComma(String(countVenMon(myBankData.value.min_usdt)))
  } else {
    return verifyNumberComma(String(myBankData.value.min_withdraw_money))
  }

}
// const closeCalibraWin = () => {
//   calibrationVisible.value = false
// }

const infoTimer: any = ref(null)
const goToWithdrawInfo = () => {
  clearTimeout(infoTimer.value);
  infoTimer.value = setTimeout(() => {
    router.replace(`/withdrawal/info`)
  }, 500)
}

watch(
  () => calibrationVisible.value,
  (n) => {
    if (!n) {
      addBankCardVisible.value = false; // 不能同时打开
    }
  }
);
watch(() => roleInfo.value.money, (n) => {
  if (!n) { // 在提款弹窗中把携带钱包中的钱全部转入保险柜，关闭弹窗
    showSafeBox.value = false
  }
})
watch(
  () => bankCardInfoList.value,
  (n) => {
    handleMyBankList(n)
    console.log('==提现列表=', n)
  }
);

const  goToReplace = () => {
  router.replace('/withdrawals')
}

const loaded = ref(false)
onMounted(() => {
  setTimeout(() => { // 奇怪的bug  PC-3115  当作浏览器自动填充处理
    loaded.value = true
    form.value.amount = ''
  }, 100)
  setTimeout(() => {
    initReq()
    getMyBankList()
    getMyUsdtList()
    getUsdtRate()
  }, 1);
  

  eventBus.on('msg_notify_del_bank_card_info', handleDelBankList)
  eventBus.on('msg_notify_set_default_bankcard', handleDefaultBank)
})

onUnmounted(() => {
  clearTimeout(infoTimer.value);
  eventBus.off('msg_notify_del_bank_card_info', handleDelBankList)
  eventBus.off('msg_notify_set_default_bankcard', handleDefaultBank)
})


</script>

<style scoped lang="scss">
@use "./form.scss";

.withdrawals_box {
  // height: calc(var(--vh) * 100 - 70px);
  overflow-y: auto;
  color: #fff;
  font-size: 14px;
  font-weight: 400;
  padding-top: 44px;

  .head {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background: url('/imgs/home/public_bg.webp');
    background-size: 80%;
    z-index: 2;
    padding: 0 15px;
  }

  :deep(.nut-popup) {
    background: none;
  }

  .flex {
    display: flex;
  }

  .justify-center {
    justify-content: center;
  }

  .justify-between {
    justify-content: space-between;
  }

  .right_handler {
    display: flex;
    gap: 15px;
  }

  .nut-input,
  select {
    width: 100%;
    border: 1px solid #333260;
    background: #1D1C3C;
    border-radius: 8px;
    padding: 11px 10px;
    height: 44px;

    //:deep(input) {
    //  &::placeholder {
    //    color: #504F6F;
    //  }
    //}
  }

  .content {
    padding: 16px 14px 30px;
    position: relative;

    .daiwancheng {
      font-size: 12px;
      position: absolute;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, 0.5);
      width: 100%;
      height: 100%;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .refresh {
    animation: refresh 1s linear infinite;
  }

  @keyframes refresh {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  .bg_color {
    background: #131232;
    box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
    border-radius: 8px;
    padding: 16px 20px;
  }

  .withDraw_top {
    position: relative;
    height: 124px;

    .label_txt {
      position: relative;
      display: flex;
      justify-content: space-between;
      padding-bottom: 12px;

      >div {
        display: flex;
        align-items: center;
        flex: 1;
      }

      .to_page {
        flex: none;
        width: auto;
        min-width: 56px;
        height: 28px;
        align-items: center;
        justify-content: center;
      }

      p {
        white-space: nowrap;
        font-size: 16px;
        font-weight: 500;

        &.mon {
          font-weight: 600;
          color: #FF9F69;
        }
      }

      &::after {
        content: '';
        width: 100%;
        height: 1px;
        position: absolute;
        background: #1D1B43;
        bottom: 0;
      }
    }

    .mon_sec {
      padding-top: 10px;

      .flex {
        margin-bottom: 3px;
        display: flex;
        justify-content: space-between;

        p:last-child {
          display: flex;
          color: #C6C4F5;
        }
      }
    }
  }

  .form_third {
    max-height: 332px;
  }

  form {
    .form_center {
      margin: 12px 0;
      height: 105px;

      :deep(.nut-cell) {
        margin-bottom: 0 !important;
      }
    }

    :deep(.nut-cell-group__wrap) {
      box-shadow: none;
      background: none;
      margin: 0;

      .nut-cell {
        background: none;
        padding: 0 !important;

        .hideInput {
          position: absolute;
          opacity: 0;
        }

        &::after {
          border: none;
        }
      }
    }

    :deep(.nut-cell__title) {
      color: #fff;
      font-size: 14px;
      padding-right: 0;
    }

    .label_capital {
      position: relative;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .switch_password,
      .zw_btn {
        width: 36px;
        height: 16px;
      }

      .zw_btn {
        position: absolute;
        z-index: 1;
        right: 0;
      }

      :deep(.switch_password) {
        --nut-switch-inside-open-transform: translateX(170%);
        --nut-switch-inside-close-transform: translateX(10%);
      }
    }

    .change_bank {
      height: 44px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #282747;
      border: 1px solid #333260;
      border-radius: 8px;
      padding: 6px 4px;

      .selectBank {
        display: flex;
        align-items: center;
        cursor: pointer;
        max-width: 240px;
        height: 44px;
        border-radius: 8px;
        //border: 1px solid #333260;

        .bankName {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 82px;
          height: 30px;
          padding: 0 4px;
          margin-right: 6px;
          //margin-left: 6px;
          border-radius: 6px;
          background: #333259;

          .icon {
            width: 18px;
            height: 18px;
            margin-right: 5px;
            background-color: #fff;
            border-radius: 50%;
            border: 1px solid #D6CDFF;

            img {
              width: 16px;
              border-radius: 50%;
            }
          }

          span {
            font-size: 12px;
            color: #fff;
            width: calc(110px - 18px);
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }

        .mantissa {
          font-weight: 400;
          font-size: 12px;
          color: #C6C4F5;
          max-width: 240px;
          word-break: break-all;
        }
      }
    }

    .label_top {
      margin-bottom: 10px;

      a:last-child {
        color: #5B6CFF;
      }
    }

  }

  .projected {
    font-size: 12px;
    color: #60d580;
    margin: 0 0 8px;

    span {
      display: flex;
      margin-left: 4px;

      :deep(.nut-popover-wrapper) {
        display: flex;
      }
    }
  }

  .tips {
    line-height: 14px;
    display: flex;
    justify-content: center;
    color: #D16262;
    font-size: 12px;
    font-weight: 400;
  }
}

.body_sec {
  .refresh_icon {
    display: inline-block;
    //width: 24px;
    //height: 24px;
  }

  .kjje_div {
    margin-bottom: 6px;
    display: flex;
    flex-wrap: wrap;
    justify-content: start;

    .kj_item {
      width: 97px;
      //width: calc((100% - 8px * 2) / 3);
      /* 每列占1/3宽度，减去间距 */
      height: 44px;
      line-height: 44px;
      text-align: center;
      background: #1D1C3C;
      box-shadow: 0.5px 0.5px 1px 0 #333260 inset;
      border-radius: 8px;
      margin-right: 8px;
      margin-bottom: 8px;
      /* 设置水平和垂直间距 */

      &:nth-child(3n) {
        margin-right: 0;
        /* 每行最后一个元素移除右间距 */
      }
    }
  }
}

.button_color {
  width: auto;
  padding: 0 14px;
}

// 默认按钮样式
.change_btn {
  border-radius: 8px;
  font-size: 14px;
  width: auto;
  min-width: 56px;
  height: 28px;
  line-height: 28px;
  padding: 0 14px;
  border: 0;

  &:active {
    color: #fff;
    border: 0;
  }

  //.icon_jt {
  //  transform: rotate(90deg);
  //}
  //:deep(.nut-button__wrap) {
  //  transform: scaleX(-1);
  //  .nut-button__text {
  //    transform: scaleX(-1);
  //  }
  //}
}

.pop_content {
  font-size: 12px;
  width: 194px;
  height: 82px;
  color: #C6C4F5;
  padding: 13px;
  background: url(/imgs/payment/dropdown.webp) center no-repeat;
  background-size: 100%;
  text-align: center;
}
</style>